package com.guchenbo.lssp.pool;

import com.guchenbo.lssp.core.Session;
import com.guchenbo.lssp.core.Statement;
import com.guchenbo.lssp.exception.SessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PooledSession extends Session {
    protected static final Logger log = LoggerFactory.getLogger(PooledSession.class);

    private SessionHolder holder;

    public PooledSession(SessionHolder holder, LivyHelper livyHelper) {
        super(livyHelper);
        this.holder = holder;
        setId(holder.getSession().getId());
    }

    public SessionHolder getHolder() {
        return holder;
    }

    public void setHolder(SessionHolder holder) {
        this.holder = holder;
    }

    public Long getSessionId() {
        return holder.getSession().getId();
    }

    @Override
    public Statement createStatement(String sql) throws SessionException {
        try {
            return holder.getSession().createStatement(sql);
        } catch (SessionException e) {
            handleException(e);
            throw e;
        }
    }

    private void handleException(Exception e) {
        log.warn("handleException {}", e.getMessage());
        holder.setDiscard(true);
    }

    public void close() {
        if (holder == null) {
            return;
        }
        holder.getSessionSource().recycle(this);
    }
}
